package com.dm.voicesubtitle.gui;

import com.dm.voicesubtitle.config.AppConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.util.Map;

/**
 * 控制面板
 */
public class ControlPanel extends JPanel {
    private static final Logger logger = LoggerFactory.getLogger(ControlPanel.class);
    
    private JButton startButton;
    private JButton stopButton;
    private JComboBox<String> languageComboBox;
    private JLabel statusLabel;
    private JButton settingsButton;
    private JButton clearButton;
    
    private ActionListener startButtonListener;
    private ActionListener stopButtonListener;
    private ActionListener languageChangeListener;
    
    public ControlPanel() {
        initializeComponents();
        setupLayout();
        setupEventHandlers();
    }
    
    /**
     * 初始化组件
     */
    private void initializeComponents() {
        // 开始按钮
        startButton = new JButton("开始录音");
        startButton.setBackground(new Color(76, 175, 80));
        startButton.setForeground(Color.WHITE);
        startButton.setFont(new Font("微软雅黑", Font.BOLD, 14));
        startButton.setPreferredSize(new Dimension(100, 35));
        
        // 停止按钮
        stopButton = new JButton("停止录音");
        stopButton.setBackground(new Color(244, 67, 54));
        stopButton.setForeground(Color.WHITE);
        stopButton.setFont(new Font("微软雅黑", Font.BOLD, 14));
        stopButton.setPreferredSize(new Dimension(100, 35));
        stopButton.setEnabled(false);
        
        // 语言选择下拉框
        languageComboBox = new JComboBox<>();
        languageComboBox.setFont(new Font("微软雅黑", Font.PLAIN, 12));
        languageComboBox.setPreferredSize(new Dimension(120, 30));
        populateLanguageComboBox();
        
        // 状态标签
        statusLabel = new JLabel("就绪");
        statusLabel.setFont(new Font("微软雅黑", Font.PLAIN, 12));
        statusLabel.setForeground(Color.GRAY);
        
        // 设置按钮
        settingsButton = new JButton("设置");
        settingsButton.setFont(new Font("微软雅黑", Font.PLAIN, 12));
        settingsButton.setPreferredSize(new Dimension(60, 30));
        
        // 清除按钮
        clearButton = new JButton("清除");
        clearButton.setFont(new Font("微软雅黑", Font.PLAIN, 12));
        clearButton.setPreferredSize(new Dimension(60, 30));
    }
    
    /**
     * 设置布局
     */
    private void setupLayout() {
        setLayout(new FlowLayout(FlowLayout.CENTER, 10, 5));
        setBorder(BorderFactory.createEmptyBorder(5, 10, 5, 10));
        setBackground(new Color(245, 245, 245));
        
        // 添加组件
        add(new JLabel("语言:"));
        add(languageComboBox);
        add(startButton);
        add(stopButton);
        add(statusLabel);
        add(settingsButton);
        add(clearButton);
    }
    
    /**
     * 设置事件处理器
     */
    private void setupEventHandlers() {
        // 开始按钮事件
        startButton.addActionListener(e -> {
            if (startButtonListener != null) {
                startButtonListener.actionPerformed(e);
            }
        });
        
        // 停止按钮事件
        stopButton.addActionListener(e -> {
            if (stopButtonListener != null) {
                stopButtonListener.actionPerformed(e);
            }
        });
        
        // 语言选择事件
        languageComboBox.addActionListener(e -> {
            if (languageChangeListener != null) {
                languageChangeListener.actionPerformed(e);
            }
        });
        
        // 设置按钮事件
        settingsButton.addActionListener(e -> showSettingsDialog());
        
        // 清除按钮事件
        clearButton.addActionListener(e -> {
            // 这里可以添加清除字幕的功能
            logger.info("清除字幕");
        });
    }
    
    /**
     * 填充语言下拉框
     */
    private void populateLanguageComboBox() {
        Map<String, AppConfig.LanguageConfig> languages = AppConfig.getInstance().getSupportedLanguages();
        
        for (AppConfig.LanguageConfig language : languages.values()) {
            languageComboBox.addItem(language.getChineseName() + " (" + language.getCode() + ")");
        }
        
        // 设置默认选择
        languageComboBox.setSelectedIndex(0);
    }
    
    /**
     * 设置录音状态
     */
    public void setRecordingState(boolean isRecording) {
        startButton.setEnabled(!isRecording);
        stopButton.setEnabled(isRecording);
        
        if (isRecording) {
            statusLabel.setText("录音中...");
            statusLabel.setForeground(new Color(76, 175, 80));
        } else {
            statusLabel.setText("就绪");
            statusLabel.setForeground(Color.GRAY);
        }
    }
    
    /**
     * 获取选中的语言代码
     */
    public String getSelectedLanguage() {
        String selectedItem = (String) languageComboBox.getSelectedItem();
        if (selectedItem != null) {
            // 从显示文本中提取语言代码
            int startIndex = selectedItem.lastIndexOf("(") + 1;
            int endIndex = selectedItem.lastIndexOf(")");
            if (startIndex > 0 && endIndex > startIndex) {
                return selectedItem.substring(startIndex, endIndex);
            }
        }
        return "zh-CN"; // 默认返回中文
    }
    
    /**
     * 显示设置对话框
     */
    private void showSettingsDialog() {
        SettingsDialog dialog = new SettingsDialog((JFrame) SwingUtilities.getWindowAncestor(this));
        dialog.setVisible(true);
    }
    
    // 事件监听器设置方法
    public void addStartButtonListener(ActionListener listener) {
        this.startButtonListener = listener;
    }
    
    public void addStopButtonListener(ActionListener listener) {
        this.stopButtonListener = listener;
    }
    
    public void addLanguageChangeListener(ActionListener listener) {
        this.languageChangeListener = listener;
    }
    
    /**
     * 设置对话框
     */
    private static class SettingsDialog extends JDialog {
        public SettingsDialog(JFrame parent) {
            super(parent, "设置", true);
            
            setSize(400, 300);
            setLocationRelativeTo(parent);
            setLayout(new BorderLayout());
            
            // 创建设置面板
            JTabbedPane tabbedPane = new JTabbedPane();
            tabbedPane.addTab("显示设置", createDisplaySettingsPanel());
            tabbedPane.addTab("音频设置", createAudioSettingsPanel());
            tabbedPane.addTab("识别设置", createSpeechSettingsPanel());
            
            add(tabbedPane, BorderLayout.CENTER);
            
            // 添加按钮
            JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
            JButton saveButton = new JButton("保存");
            JButton cancelButton = new JButton("取消");
            
            saveButton.addActionListener(e -> {
                // 保存设置
                AppConfig.getInstance().saveConfig();
                dispose();
            });
            
            cancelButton.addActionListener(e -> dispose());
            
            buttonPanel.add(saveButton);
            buttonPanel.add(cancelButton);
            add(buttonPanel, BorderLayout.SOUTH);
        }
        
        private JPanel createDisplaySettingsPanel() {
            JPanel panel = new JPanel(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.insets = new Insets(5, 5, 5, 5);
            gbc.anchor = GridBagConstraints.WEST;
            
            AppConfig.DisplayConfig config = AppConfig.getInstance().getDisplayConfig();
            
            // 字体大小
            gbc.gridx = 0; gbc.gridy = 0;
            panel.add(new JLabel("字体大小:"), gbc);
            
            gbc.gridx = 1;
            JSpinner fontSizeSpinner = new JSpinner(new SpinnerNumberModel(config.getFontSize(), 12, 48, 2));
            panel.add(fontSizeSpinner, gbc);
            
            // 字幕持续时间
            gbc.gridx = 0; gbc.gridy = 1;
            panel.add(new JLabel("字幕持续时间(秒):"), gbc);
            
            gbc.gridx = 1;
            JSpinner durationSpinner = new JSpinner(new SpinnerNumberModel(config.getSubtitleDuration() / 1000, 1, 10, 1));
            panel.add(durationSpinner, gbc);
            
            // 多语言支持
            gbc.gridx = 0; gbc.gridy = 2;
            panel.add(new JLabel("启用多语言:"), gbc);
            
            gbc.gridx = 1;
            JCheckBox multiLanguageCheckBox = new JCheckBox("", config.isEnableMultiLanguage());
            panel.add(multiLanguageCheckBox, gbc);
            
            return panel;
        }
        
        private JPanel createAudioSettingsPanel() {
            JPanel panel = new JPanel(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.insets = new Insets(5, 5, 5, 5);
            gbc.anchor = GridBagConstraints.WEST;
            
            AppConfig.AudioConfig config = AppConfig.getInstance().getAudioConfig();
            
            // 采样率
            gbc.gridx = 0; gbc.gridy = 0;
            panel.add(new JLabel("采样率:"), gbc);
            
            gbc.gridx = 1;
            JComboBox<Integer> sampleRateComboBox = new JComboBox<>(new Integer[]{8000, 16000, 44100, 48000});
            sampleRateComboBox.setSelectedItem(config.getSampleRate());
            panel.add(sampleRateComboBox, gbc);
            
            return panel;
        }
        
        private JPanel createSpeechSettingsPanel() {
            JPanel panel = new JPanel(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.insets = new Insets(5, 5, 5, 5);
            gbc.anchor = GridBagConstraints.WEST;
            
            AppConfig.SpeechConfig config = AppConfig.getInstance().getSpeechConfig();
            
            // 自动语言检测
            gbc.gridx = 0; gbc.gridy = 0;
            panel.add(new JLabel("自动语言检测:"), gbc);
            
            gbc.gridx = 1;
            JCheckBox autoLanguageCheckBox = new JCheckBox("", config.isEnableAutoLanguageDetection());
            panel.add(autoLanguageCheckBox, gbc);
            
            return panel;
        }
    }
} 